<template>
  <van-icon
    :color="attitude === 1 ? '#ff0000' : '#777'"
    :name="attitude ? 'good-job' : 'good-job-o'"
    @click="changeFollowed"
  />
</template>

<script>
import { addLikeAPI, deleteLiketAPI } from '../api/index.js'
export default {
  name: 'CollectArticle',
  // model: {
  //     prop: 'isFollowed',
  //     event: 'update-follow'
  // },
  props: {
    attitude: { // 是否关注
      type: Number,
      default: -1
    },
    artId: { // 用户id
      type: String,
      default: ''
    }
  },
  data () {
    return {
      btnLoading: false
    }
  },
  methods: {
    // 切换关注状态
    async changeFollowed () {
      if (this.btnLoading) return

      this.btnLoading = true // 展示关注按钮的 loading 状态

      try {
        if (this.attitude === 1) {
          // 已关注，取消关注
          await deleteLiketAPI(this.artId)
        } else {
          // 没有关注，添加关注
          await addLikeAPI(this.artId)
        }
        // 更新视图 让父组件去完成关注状态的变化
        // this.$emit('update-follow', !this.isCollected)
        this.$emit('update:attitude', this.attitude === 1 ? -1 : 1)
        this.$toast(this.attitude !== 1 ? '点赞成功' : '取消点赞')
      } catch (err) {
        this.$toast('操作失败')
      }
      this.btnLoading = false // 关闭关注按钮的 loading 状态
    }
  }
}
</script>

<style lang="less" scoped>
</style>
